package com.calvin.study.multithread.threadutils;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

import com.calvin.study.utils.ThreadUtil;

import cn.hutool.core.util.RandomUtil;

//有20个计算任务，我们需要先将这些任务的结果全部计算出来，每个任务的执行时间未知
//当所有任务结束之后，立即整合统计最终结果
public class CountDownLatchDemo03 {

	static int count = 0;

	public static void main(String[] args) throws InterruptedException {

		CountDownLatch cdl = new CountDownLatch(20);
		for (int i = 1, len = 20; i <= len; i++) {
			int num = i;
			new Thread(() -> {
				try {
					Double runTime = 2000 * RandomUtil.randomDouble();
					ThreadUtil.sleepMilliSeconds(runTime.intValue());
					count = count + num;
					System.out.println("子任务" + num + "执行完成，运行时间：" + runTime.intValue()+"ms");
					cdl.countDown();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}, String.valueOf(i)).start();
		}
		//等待所有线程运行完成
		cdl.await();
		System.out.println("任务完成，最终结果：" + count);
	}

}
